Virtual Types are Statically Safe
نویسنده
چکیده
Point = fx,y: Integer;CompareType <= Point;equal(p: CompareType): Bool freturn (this.x=p.x) and (this.y=p.y);ggPoint = AbstractPoint fCompareType = Point;gColourPoint = AbstractPoint fc: Color;CompareType = ColourPoint;equal(p: CompareType): Bool freturn super.equal(p) and (this.c = p.c);gg Figure 13: A slight change xes the problemOn top of this comes the fact that Point may now beused in a safe way, and that references to Points that cannot contain ColourPoints are now possible.AbstractPoint = fx,y: Integer;CompareType <= Point;equal(p: CompareType): Bool freturn (this.x=p.x) and (this.y=p.y);ggPoint = AbstractPoint fCompareType = AbstractPoint;gColourPoint = AbstractPoint fc: Color;CompareType = AbstractPoint;g Figure 14: A di erent choice of semanticsFurthermore the programmer now has the full choice ofwhether or not to allow Points and ColourPoints to be com-pared with each other. If this should be possible, theseclasses should just nal bind CompareType to AbstractPointinstead of to themselves, as shown in Figure 14. The twoclasses could even have di erent semantics, so that a Pointwill accept a ColourPoint, but not vice versa { the choicebelongs entirely to the programmer.This restructuring is always possible: If you need a con-crete version of a class that has open virtual types, make aconcrete subclass of it, where you nal bind all the virtuals.If the creation of such trivial subclasses proves too tedious,one might consider simply adding a language construct fordoing it automatically.In our opinion, this cuts the Gordian knot.7 Related workThe covariance problem as exempli ed through the Colour-Point example, has been treated in numerous ways over thepast decade or so. This section relates some of the proposedsolutions to the one presented here.7.1 Separating subclassing and subtypingDue to the covariance problem, it was proposed in [4] toseparate the subtype and subclass relations. This has theappeal that a variable declared by a given type does notneed to be able to hold all subclasses of an associated class,but only those that are known to be substitutable for thedeclared type.In Emerald [10] and many theoretical languages (suchas LOOM [2]) this lead to a complete separation of classes(that describe implementation) and types (that describe in-terface), which in turn leads to quite a speci cation overheadwhen types and classes coincide.To avoid this, Sather [16] reuni es types and classes, andonly separate the two relations, subtyping and subclassing.Clearly, stepping down on the demand that subclassingyields subtyping, gives new possiblities for static type check-ing. It is not without problems however { keeping track oftwo di erent but closely related relations can be confusingin practice.A more profound objection seen from our point of viewaims at the way this solution views inheritance: Primarilyas a code reuse mechanism. Instead of modelling a concep-tually clear specialization relation, subclassing is an ad hocrelationship between classes. This is why the need is felt fora seperate, \cleaner" relation.From the perspective of this article, subtyping and theconceptual specialization relation coincide, and inheritanceshould only be allowed to be used in this way. As seen inSection 6, this does not prohibit the reuse of code, it justrequires it to occur in a slightly more structured way: as in-heritance of a common ancestor rather that as conceptuallyunsound inheritance from \cows to horses".7.2 Monomorphic typesCovariance is only a problem because references to classeswith covariant parameter types may contain instances ofsubtypes. Some solutions therefore introduce various con-structs to avoid the unfortunate consequences of subtypesubstitutability in certain cases { in other words to havemonomorphically as well as polymorphically typed variables.Building on a proposal by Dodani and Tsai [5], Sather[16] divides classes into abstract and concrete, of which onlythe latter can be instantiated. While concrete classes canhave subclasses, they do not have any subtypes. For thisreason a variable qualifed by a concrete type can only referobjects of exactly that class.This is reminiscent of Java's nal classes [9], which pro-hibit further specialization, and thus make references quali-ed by them monomorphic.A di erent way to do this is to let the references them-selves be declared type exact. This is the case with partobjects in Beta [12] and with exact types in LOOM, wheresubtyping has been completely dropped in favour of match-ing; see below.For describing instances of concrete classes, which in anatural way often are (or should be) leaf classes, monomor-phism seems like a sensible idea, although it appears to besomewhat vulnarable to later redesigns of the kind where5 7 one concrete class is turned into an abstract one to intro-duce di erent variants as subclasses.The reason why it is not considered in our langauageis that it is not necessary. Since all virtual types can benal bound, a concrete subclass without covariant parame-ters can aways be declared. As opposed to a nal class, sucha \ nalized" class (like Cow in Section 2.1) can have sub-classes (like DairyCow, Hereford etc.), and references qualifedby it can refer to instances of these subclasses.7.3 MatchingAnother approach is to say: well, if inheritance does notgive us subtyping, what does it give us then? The answer ismatching [1, 2]. In LOOM references can be qualifed withso called \hash types", say #C, which cover any classes thatmatch C, that is, all subclasses of C. A reference to a hashtype is restricted so that only methods without covariantparameters can be called on it. Therefore the covarianceproblem does not occur.In LOOM, If you want to refer only to Points you usethe type Point (which is monomorphic), while if you want torefer also to ColourPoints you use the type #Point, but arethen not allowed to call a covariant equal method on it.Notice how closely this corresponds to Point and Ab-stractPoint respectively in our solution. The only di erenceseems to be that we have to declare an extra class, but onthe other hand get polymorphism on references to Point,plus the ability to call equal on AbstractPoint in special sit-uations, as described in Section 5.3.8 GenericityThis paper has mainly focused on the covariance issues ofvirtual types.Virtual types as an alternative genericity mechanism toparameterized types (as in Ei el [15], C++ [7] and manyothers) is usually criticized because of it's alleged depen-dence on dynamic typechecking. With this proposal thatargument loses validity { as for static type safety, virtualtypes must now be seen as an equally valid choice.Yet, rather than looking at virtual and parameterizedtypes as contenders, it is compelling to ponder the possi-bilities of combining the strengths of the two approaches.While it is certainly outside the scope of this paper to givea proper proposal for such a fusion, it should be noted inpassing, that the statical safety of virtual types brings it alot closer.9 Riding the Java TrainJava currently supports neither genericity nor covariance.Since these are issues that many people have opinions about,a lot of di erent proposals are currently being made foradding such facilities one way or the other.And yes, a proposal for adding virtual types to Java hasalso come forth [18]. While blending very elegantly into thesyntactic framework of Java, and { as it seems { neatly t-ting the virtual types in with particular Java constructs suchas interfaces and abstract classes, this otherwise convincingproposal has one serious drawback: It requires implicit dy-namic type checking.In Beta all so called reverse assignments2 are staticallyallowed, but subjected to a runtime type check. The run-2Assignments from general to more special typestime checking introduced by virtual types ts nicely into thisscheme, and can be seen as a special case.Java, however, is a fully statically type checked language.With the one unfortunate exception of arrays, which arecovariant and require dynamic checks, runtime checking oftypes can only come about as a result of explicit type casts inthe code. The introduction of implicit runtime checks wouldprofoundly violate this very deliberate principle of Java.This is where the cavalry comes in. If the type checkingscheme proposed here expands well to Java, this last prob-lem is overcome. To gain further insight into this, staticallysafe virtual types are currently being added to an experi-mental compiler for the JOOS subset of Java (generouslyprovided by Michael Schwartzbach and Laurie Hendren).This implementation project will serve as a proof of con-cept both of the feasibility of virtual types in Java and ofthe practicality of the type checking scheme of this paper.10 ConclusionThe main conclusion to draw from this paper is that covari-ance, static type safety and subtype substitutability are notincompatible after all. But to make them coexist withoutlosing out fatally on expressiveness, a mechanism must beprovided to control covariance, and programmers need to beaware of its impact on type checking.The type checking framework in Section 5 is to the bestof our knowledge the rst in-depth account of a type check-ing mechanism for a language with virtual types. Since thepermission of dynamic checks is merely a matter of modi-fying the subtype relation <:, the approach might inspire amore formal description of e.g. the Beta type system, al-though admittedly the presence of block structure probablycomplicates matters somewhat.While resting heavily on the presence of nal bindingsfor safety, the proposed solution to the ColourPoint problem(Figure 13) in our oppinion also points to a more philosoph-ical consideration. The inheritance relation prescribed bythe original version re ects a simple minded desire for codereuse. Whether or not it is meaningful to say that Colour-Points actually are Points, and to what extend sensible se-mantics for comparing the two di erent kinds of objects mayexist, is not at all considered.Taking a conceptual view, we think that { even withoutthe type safety { the new version is how we would havemodelled the situation. This is just one example of whatin our experience { but this is just a gut feeling { seemsto be a common pattern: That conceptual modelling andtype-theoretic soundness tend to go hand in hand.References[1] Abadi, M., and Cardelli, L. On subtyping andmatching. In ECOOP'95 { Object-Oriented Program-ming (1995), pp. 145{167.[2] Bruce, K. B. Subtyping is not a good \match" forobject-oriented languages. In ECOOP'97 { Object-Oriented Programming (1997), M. Aksit and S. Mat-suoka, Eds., no. 1241 in Lecture Notes on ComputerScience, Springer, pp. 104{127.[3] Bruce, K. B., Cardelli, L., Castagna, G., TheHopkins Object Group, Leavens, G. T., andPierce, B. On binary methods. Theory and Practiceof Object Systems, 1 (1995), 221{242.5 8 [4] Cook, W. R., Hill, W. L., and Canning, P. S.Inheritance is not subtyping. In ACM Conferenceon Principles of Programming Languages (POPL'90)(1990), ACM Press, pp. 125{135.[5] Dodani, M., and Tsai, C.-S. Acts: A type systemfor object-oriented programming based on abstract andconcrete classes. In ECOOP'92 { Object-Oriented Pro-gramming (1992), O. L. Madsen, Ed., no. 615 in LectureNotes in Computer Science, Springer, pp. 309{328.[6] Drossopoulou, S., and Eisenbach, S. Java is typesafe probably. In ECOOP'97 { Object-Oriented Pro-gramming (1997), M. Aksit and S. Matsuoka, Eds.,no. 1241 in Lecture Notes on Computer Science,Springer, pp. 389{418.[7] Ellis, M. A., and Stroustrup, B. The AnnotatedC++ Reference Manual. Addison-Wesley, 1990.[8] Goldberg, A., and Robson, D. Smalltalk-80 { TheLanguage. Addison-Wesley, 1989.[9] Gosling, J., Joy, B., and Steele, G. The JavaLanguage Speci cation. Addison-Wesley, 1996.[10] Hutchinson, N. Emerald: An Object-Oriented Lan-guage for Distributed Programming. PhD thesis, De-partment of Computer Science, University of Washing-ton, Seattle, WA, January 1987.[11] Madsen, O. L. Open issues in object-orientedprogramming{a scandinavian perspective. Software{Practice and Experience 25, S4 (December 1995).[12] Madsen, O. L., Magnusson, B., and M ller-Pedersen, B. Strong typing of object-oriented lan-guages revisited. In Proceedings of OOPSLA'90 (Ot-tawa, Canada, 1990), SIGPLAN, ACM Press.[13] Madsen, O. L., and M ller-Pedersen, B. Virtualclasses: A powerful mechanism in object-oriented pro-gramming. In Proceedings of OOPSLA'89 (1989), SIG-PLAN, ACM Press.[14] Madsen, O. L., M ller-Pedersen, B., and Ny-gaard, K. Object-Oriented Programming in the BETAProgramming Language. Addison-Wesley, 1993.[15] Meyer, B. Object-Oriented Software Construction.Prentice Hall International Series in Computer Science.Prentice Hall, Englewood Cli s, NJ, 1988.[16] Omohundro, S. The Sather Programming Language.Dr. Dobb's Journal 18, 11 (October 1993).[17] Shang, D. Are cows animals? Object Currents 1, 1(January 1996). http://www.sigs.com/objectcurrents/.[18] Thorup, K. K. Genericity in java with virtual types.In ECOOP'97 { Object-Oriented Programming (1997),M. Akit and S. Matsuoka, Eds., no. 1241 in LectureNotes on Computer Science, Springer, pp. 444{471.5 9
منابع مشابه
A Statically Safe Alternative to Virtual Types
Parametric types and virtual types have recently been proposed as extensions to Java to support genericity. In this paper we investigate the strengths and weaknesses of each. We suggest a variant of virtual types which has similar expressiveness, but supports safe static type checking. This results in a language in which both parametric types and virtual types are well-integrated, and which is ...
متن کاملSemantics-Driven Language Design: Statically Type-safe Virtual Types in Object-oriented Languages
The virtual class 15] construct was rst introduced in the language Beta to provide added expressiveness when used with inheritance. Unfortunately, the virtual class construct in Beta is not statically type-safe. In this paper we show how a generalization of the semantics of object-oriented languages with a MyType construct leads to a variant of virtual classes which needs no run-time checks. Th...
متن کاملUnifying Genericity - Combining the Benefits of Virtual Types and Parameterized Classes
Generic types in programming languages are most often supported with various forms of parametric polymorphism, i.e. functions on types. Within the framework of object-oriented languages, virtual types present an alternative where specific types are derived from generic ones using inheritance rather than function application. While both mechanisms are statically safe and support basic genericity...
متن کاملSafe Runtime Downcasts With Ownership Types
The possibility of aliasing between objects constitutes one of the primary challenges in understanding and reasoning about correctness of object-oriented programs. Ownership types provide a principled way of specifying statically enforcable restrictions on object aliasing. Ownership types have been used to aid program understanding and evolution, verify absence of data races and deadlocks in mu...
متن کاملOptimizing Dynamic Class Composition in a Statically Typed Language
In statically typed languages the set of classes and similar classifiers is commonly fully determined at compile time. Complete classifier representations can then be loaded at run-time, e.g., from a an executable file or a class file. However, some typing constructs—such as virtual classes—enable a type safe treatment of classifiers and their associated types and instances, even in the case wh...
متن کاملLocation Types for Safe Distributed Object-Oriented Programming
In distributed object-oriented systems, objects belong to different locations. For example, in Java RMI, objects can be distributed over different JVM instances. Accessing a reference in RMI has crucial different semantics depending on whether the referred object is local or remote. Nevertheless, such references are not statically distinguished by the type system. This paper presents location t...
متن کامل